﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace iLangl
{
	public class BaseContext  : IContext
	{
		public event EventHandler ContextUpdated;

		protected StringBuilder result = null;
		protected XmlWriter writer = null;


		protected void startDocument()
		{
			CreateXmlWriter(out result, out writer);

			writer.WriteStartDocument();
		}

		protected String endDocument()
		{
			writer.WriteEndDocument();
			writer.Flush();
			return result.ToString();
		}
	
		protected void CreateXmlWriter(out StringBuilder result, out XmlWriter writer)
		{
			XmlWriterSettings settings = new XmlWriterSettings();
			settings.Indent = true;
			settings.OmitXmlDeclaration = true;
			settings.NewLineOnAttributes = true;

			result = new StringBuilder();


			writer = XmlWriter.Create(result, settings);
		}

		

		#region IContext Members
		object _context;
		public virtual void SetContext(object context)
		{
			_context = context;

		}

		

		protected void FireChanges()
		{
			if (ContextUpdated != null)
				ContextUpdated(this, EventArgs.Empty);
		}

		public virtual object GetContext()
		{
			return _context;
		}

		public virtual String GetExtendedAttributes(object obj)
		{
			if (obj is IDuplex)
			{
				IDuplex duplex = obj as IDuplex;

				return String.Format(" CustomerIdentity='{0}' TPIdentity='{1}'", duplex.CustomerIdentity, duplex.TPIdentity);
			}

			return String.Empty;
		}

		


		public virtual void InitExtendedAttributes(XmlWriter xmlWriter, object obj)
		{
			if (obj is IDuplex)
			{
				IDuplex duplex = obj as IDuplex;

				xmlWriter.WriteAttributeString("CustomerIdentity", duplex.CustomerIdentity);
				xmlWriter.WriteAttributeString("TPIdentity", duplex.TPIdentity);
			}

		}

		public virtual void ParseExtendedInfo(XmlNode xmlNode, object obj)
		{
			if (xmlNode == null)
				return;

			if (obj is IDuplex)
			{
				IDuplex duplex = obj as IDuplex;

				if (xmlNode.Attributes["CustomerIdentity"] != null)
					duplex.CustomerIdentity = xmlNode.Attributes["CustomerIdentity"].Value;

				if (xmlNode.Attributes["TPIdentity"] != null)
					duplex.TPIdentity = xmlNode.Attributes["TPIdentity"].Value;
			}
		}

		public virtual void ParseExtendedInfo(XmlNode xmlNode)
		{
			ParseExtendedInfo(xmlNode, _context);
			
		}

		public virtual String GetExtendedElements()
		{
			return String.Empty;
		}

		public virtual void InitExtendedElements(XmlNode node, object obj)
		{
			
		}

		public virtual void InitExtendedElements(XmlWriter node, object obj)
		{

		}

		public virtual void InitExtendedInfo(XmlWriter document)
		{
		}

		#endregion
	}
}
